package cn.itcast.ssm.Service;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;

@Service()
public class imgServiceImp implements imgService {
    public imgServiceImp() {
    }

    @Override
    public ArrayList getImgList(String keywords) {
        ArrayList <String> arrayList;
//                String a1 = "风景";
        Connection conn = Jsoup.connect("http://www.ivsky.com/search.php?q=" + keywords).timeout(10000);
//        Connection conn = Jsoup.connect(url); // 修改http包中的header,伪装成浏览器进行抓取
        conn.header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50");
        Document doc = null;
        try {
            doc = conn.get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Elements a = doc.select("img");
        if(a==null||a.size()==0){
            return  null ;
        }
        arrayList = new ArrayList <>();
        String url = "http://img.ivsky.com/img/bizhi/pre/";

        for (Element element : a) {
            String string = element.attr("src");

            if (string.contains("http://img.ivsky.com/img/bizhi/")) {
                String s = string.split("http://img.ivsky.com/img/bizhi/t/")[1];
                arrayList.add(url + s);
            }
        }
        return arrayList;
    }

    @Override
    public String getCYJL(String keywords) {

//                String a1 = "风景";
        Connection conn = Jsoup.connect("https://chengyujielong.51240.com/"+ keywords+"__chengyujielong/").timeout(10000);
//        Connection conn = Jsoup.connect(url); // 修改http包中的header,伪装成浏览器进行抓取
        conn.header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50");
        Document doc = null;
        try {
            doc = conn.get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element a = doc.select("ul li a").first();
        String text = a.text();
        return text;
    }


}
